MVC WebAPI returning 500 error with no information - asp.net-web-api

I've been having this problem for several days (now fixed and solution noted for anyone that comes across this issue and is pulling their hair out).
After my latest round of code changes to my Silverlight application which uses MVC4 WebAPI for data, I was having a problem with one of my HttpGet Actions which was returning IQueryable<oneofmyclasses>. Using Fiddler2 to watch the request, I could see I was getting an internal server error (500), with no body text to explain why. I received no errors thrown in my Action.
Check 1: I verified that my Action was indeed getting to the return collection.AsQueryable(); line with no errors. It was
Check 2: I verified that my data was serializing to JSON with no errors using this code (g is my collection):
var json = new JsonMediaTypeFormatter();
json.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;
ObjectContent<IEnumerable<Model.MenuGroup>> responseContent = new ObjectContent<IEnumerable<Model.MenuGroup>>(g, json);
MemoryStream ms = new MemoryStream();
responseContent.CopyToAsync(ms).Wait();
ms.Position = 0;
var sr = new StreamReader(ms);
var str = sr.ReadToEnd();
This also worked. I also tested it using XML formatter even though I was pretty sure it only ever used JSON (can't be too careful).
Check 3: Enabled .Net Framework debugging. This time when the error occured (in HttpApplication.cs) VS 2012 caught it.
My error:
Despite having marked the property with these attributes,
[XmlIgnore]
[IgnoreDataMember]
[JsonIgnore]
the .Net Source was calling a get on one of my properties. The catch, it was a write-only property. I simply added
get { return null; }
and the problem was solved.
I probably should have just done Check 3 first, but my previous experience with this error has shown it to usually be an error trying to serialize my objects, which was why I had a bit of a head scratcher when they did serialize properly and the error persisted.

How I solved it:
Enabled .Net Framework debugging. Tools -> Options -> Debugging -> Check 'Enable .NET Framework source stepping'
This time when the error occured (in HttpApplication.cs) VS 2012 caught it.

Related

Swagger getting struck when returning Microsoft.Graph.User return type

I have a default .NET 6 WebAPI project generated by VisualStudio to which I have added Microsoft.Graph nuget package
Here is my program.cs
and finally my controller
When I run this project and try to test the Get endpoint, the swagger UI is getting struck and there is no error being thrown
If I change the return type to either dynamic or object, it works as expected. Maybe I overlooking something basic but I couldn't figure out this issue. Any help is appreciated.
You can speedup rendering for complex types like Microsoft.Graph.User by disabling syntax highlight.
app.UseSwaggerUI(config =>
{
config.ConfigObject.AdditionalItems["syntaxHighlight"] = new Dictionary<string, object>
{
["activated"] = false
};
});
With this setting UI gets stuck only for 10-15 seconds.

.NET Core 5 GET Action Called Twice

Environment
.NET Core 5 Web Application
IIS 10
Azure VM
Issue
Executing a GET action results in that action being called a second time. The first call shows cookie information. The second does not show cookie information.
What we've tried:
Occurs for GET requests but not POST requests
Occurs without a view (NOT a javascript issue)
Browser does not show two requests. This occurs server-side.
Does not occur in Firefox Privacy Mode
Does not occur on localhost. Only in production.
Occurs with HTTPS off
Fork of the solution does not exhibit this behavior (makes middleware unlikely cause)
Best guesses:
.NET 5 (deprecated) or dependencies (a bad developer blames his tools)
IIS Settings
Session
Code example:
Controller
// no other filters
[HttpGet]
public IActionResult DupeRequestTest()
{
// database insert with Dapper
var sql = #"INSERT INTO TrackingTable
(CookieJson, CreateDate)
VALUES(#CookieJson, GETDATE());";
using var con = new SqlConnection(_connectionString);
con.Open();
con.Execute(sql, new
{
CookieJson=JsonConvert.SerializeObject(Request.Cookies),
});
// returning a status code so no View, javascript, or other requests
return StatusCode(200);
}
Database results:
CookieJson
CreateDate
[{"Key":"SessionId","Value":"ac6f292c-1ca1-5179-9123-78a04d382dea"}]
2022-10-25 09:46:30.523
[]
2022-10-25 09:46:30.770
Thank you. Any help, such as next testing steps, would be appreciated - short of building a new app.
I'm sure the answer is either very stupid or very hidden.

Xamarin.Auth - Google authentication won't open in browser

I'm trying to do authentication on my Android application using Xamarin.Auth. Some time ago, Google made the policy that you cannot do this in an embedded web view (for totally valid reasons).
I'm trying to open the account authentication page in a browser, but keep getting the embedded web view. I understand that isUsingNativeUI needs to be true in the following code:
_auth = new OAuth2Authenticator(clientId, string.Empty, scope,
new Uri(Constant.AuthorizeUrl),
new Uri(redirectUrl),
new Uri(Constant.AccessTokenUrl),
null,
isUsingNativeUI = true);
At every point in my application, this always equals true.
Elsewhere, I have code that redirects to what should be a browser:
var authenticator = Auth.GetAuthenticator();
Intent intent = authenticator.GetUI(this);
this.StartActivity(intent);
Regardless, I keep getting a dreaded 403 disallowed_useragent error whenever I try to run the project. Is there another element to this that I'm missing?
To my knowledge, setting auth.IsUsingNativeUI = true in the constructor should dictate that it must open in a browser. I've been following this example to try and debug with no success. I even pulled the guy's repo down to my machine and ran it - the Intent variable at the moment of redirection is almost identical.
Could there be something stupid that I'm missing? What else might be going wrong?
I realize this is an old question, but I had the same issue.
You have to install version 1.5.0.3 of the Xamarin.Auth Nuget package. The newest one (version 1.7.0 right now) doesn't work. You'll have to also install the PCLCrypto nuget package in order to get that version to work.

How can I view the request body in ASP.NET Web API from Visual Studio?

How can I view the request body in ASP.NET Web API from Visual Studio? In ASP.NET MVC, you can use QuickWatch to inspect the Request object and view the content of the body and any posted form data. From what I read, ASP.NET Web API doesn't allow you to read the body more than once.
This is very annoying to deal with when trying to figure out why a specific value wasn't bound correctly. Is there a quick way to do this without setting up tracing/logging?
The easiest it to install Fiddler. Then you will see everything that gets sent over the wire and inspect not only the request payload but the HTTP headers as well. And if you are consuming the API from javascript, things like FireBug, Chrome Developer Toolbar and IE Developer Tools will show you all network requests made by the website.
If you absolutely must inspect the traffic on the server then if you are hosting your Web API inside an ASP.NET application you could put the following line in your immediate window:
new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd()
if you need body >> Form-data
Post localhost:53356/api/carparksapi/GetRecod
key=jsonRequest and value=[{"abcd":"zxxx"}]
// API -Controller Method ::
var httpContext = (HttpContextWrapper)Request.Properties["MS_HttpContext"];
var foo = httpContext.Request.Form["jsonRequest"];
return foo; //This is value passed in request
For ASP.NET Core use this in the immediate window:
new System.IO.StreamReader(Request.Body).ReadToEnd()
For me #DarinDimitrov answer gave
error CS0246: The type or namespace name 'StreamReader' could not be found (are you missing a using directive or an assembly reference?)
Adding namespace did it
new System.IO.StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd()
Hope this saves you some time
For me #Matas Vaitkevicius answer gave
error CS1061: 'HttpContextBase' does not contain a definition for
'Current' and no extension method 'Current' accepting a first argument
of type 'HttpContextBase' could be found (are you missing a using
directive or an assembly reference?)
Replacing HttpContext.Current with System.Web.HttpContext.Current did it for me
new System.IO.StreamReader(System.Web.HttpContext.Current.Request.InputStream).ReadToEnd()
Hope this saves you some time
Any of these answers could work if the position of the steam is at position 0.
HttpContext.Current.Request.InputStream.Position = 0;
var body = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd();

Exception when deleting message from Azure queue?

I'm dipping my toes into Windows Azure, and I'm running into something that has to be simple, but I just can't see it.
I have this small test to play with Azure queues:
public void CanPublishSillyLittleMessageOnQueue()
{
var queueClient = CloudStorageAccount.DevelopmentStorageAccount.CreateCloudQueueClient();
var testQueue = queueClient.GetQueueReference("testqueue1");
testQueue.CreateIfNotExist();
var message = new CloudQueueMessage("This is a test");
testQueue.AddMessage(message);
CloudQueueMessage received;
int sleepCount = 0;
while((received = testQueue.GetMessage()) == null)
{
++sleepCount;
Thread.Sleep(25);
}
testQueue.DeleteMessage(received);
Assert.Equal(message.AsString, received.AsString);
}
It sends the message just fine - I can see it in the SQL table. However, when it hits the "testQueue.DeleteMessage(received)" method, I get this:
TestCase 'AzureExploratory.PlayingWithQueues.CanPublishSillyLittleMessageOnQueue'
failed: System.ArgumentNullException : Value cannot be null.
Parameter name: str
at Microsoft.WindowsAzure.StorageClient.Tasks.Task`1.get_Result()
at Microsoft.WindowsAzure.StorageClient.Tasks.Task`1.ExecuteAndWait()
at Microsoft.WindowsAzure.StorageClient.TaskImplHelper.ExecuteImplWithRetry(Func`1 impl, RetryPolicy policy)
at Microsoft.WindowsAzure.StorageClient.CloudQueue.DeleteMessage(CloudQueueMessage message)
PlayingWithQueues.cs(75,0): at AzureExploratory.PlayingWithQueues.CanPublishSillyLittleMessageOnQueue()
which appears to be a failure somewhere down inside the guts of the Azure SDK.
I'm using VS 2010, .NET 4.0, the Azure SDK V1.2, 64-bit Win 7. The developer store service is running; I can see the messages go into the queue, I just can't delete them.
Anyone ever seen anything like this?
I figured out what's going on. The code in question was running in a xUnit test harness. Turns out that the xUnit runner doesn't set up an appdomain with a config file path by default. System.UriBuilder now hits the config file, so it blows up.
The workaround was to add an empty app.config to the test project. Now it works.
ARGH!

Resources