ASP.NET MVC Read Raw JSON Post Data - asp.net-mvc

This is driving me crazy. I'm using ASP.NET MVC. I have a controller with an HttpPost action that acts as a callback URL that is called by another server (not under my control). I want to dynamically read JSON posted to it without using WebAPI or Model Binding. The URL also has a query string parameter passed to it.
The callback URL looks something like this:
http://domain.com/callback?secret=1234
I've tried reading the posted input using:
[HttpPost]
public ActionResult Callback( String secret )
{
String jsonData = new StreamReader(this.Request.InputStream).ReadToEnd();
// ...
}
However "jsonData" is always null or empty.
I just want to get the posted input and stick it into JsonFx so I can dynamically access the contents. Any ideas on how to do this the easiest possible way?
UPDATE
I've discovered the following ...
While the above DOES NOT work (jsonData will be null or empty), the following DOES if I configure what little options I have on the calling server so as to omit the "secret" query string parameter, which is about all I can do on that end since it is not my server. In this case, jsonData will have the correct posted JSON string:
[HttpPost]
public ActionResult Callback( /* String secret */ )
{
String jsonData = new StreamReader(this.Request.InputStream).ReadToEnd();
// ...
}
This is very frustrating to work around and I don't know an easy way to accept both a query string and posted JSON data on a standard MVC controller.
I have a "callback controller" with Action methods that accept various data (via GET, via form POST, via JSON POST, via JSON POST w/ a Query String, etc.) from different third-party servers. These are merchant-type callbacks where I have no control over the formats or methods used to convey information. I just need to accept the callbacks and process the information that should be there.
All of it works fine in my Controller, except the case of "JSON POST w/ a Query String".
This appears (at least to me) to be a shortcoming in standard ASP.NET MVC controllers. ???
Can anyone suggest a solution to this that can be used in a standard ASP.NET MVC controller?

Your initial approach should work if you take into consideration the fact, that ASP.NET MVC model binding has already read the stream, so you should rewind it:
[HttpPost]
public ActionResult Callback(string secret)
{
Request.InputStream.Seek(0, SeekOrigin.Begin);
string jsonData = new StreamReader(Request.InputStream).ReadToEnd();
// ...
}

Reset the position to Zero before reading the stream.
Request.InputStream.Position = 0

For ASP.NET Core 2,this works for me.
[HttpPost]
public ActionResult RawTest() {
using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
{
string content = reader.ReadToEndAsync().Result;
//...
}
//...
}

Related

Encrypt data passed in View Model

I have a simple post method in a MVC controller that checks whether the ModelState is valid then calls another method passing an instance of the model as a paramter. This model contains sensitive data that is easily obtained by looking at Fiddler. My goal is to somehow mask or encrypt this data so that it cannot be seen in an http trace.
I have seen posts suggesting to use Session or Temp variables but that is not an option in my case.
This is what the code looks like:
[HttpPost]
[ActionName("Search")]
[AccessControl(Xri)]
public ActionResult SearchPost(string string1, ViewModel model)
{
model.NoResults = false;
if (ModelState.IsValid)
{
if (ModelState.IsValid) return RedirectToAction("TargetAction", model);
}
}
[AccessControl(Xri)]
public ActionResult TargetAction(string arg, ViewModel viewModel)
{
.
.
.
}
Fiddler shows the following:
/TargetAction?id=01010101&date=08%2F14%2F2013%2000%3A00%3A00&To=08%2F21%2F2013%2000%3A00%3A00&param1=somevalue&param2=somevalue2
Is there a way to mask the url parameters shown here?
You're going to need to get SSL running on your server.
Without a server certificate from a trusted authority, there is very little you can do to encrypt the data over the wire. Why? Because you'd need to send encryption/decryption details in clear text before you start sending the data so that your client (likely JavaScript) could decode it.
Using a certificate and operating on 443 gives you built-in functionality from the server/browser that is hard to beat in a custom implementation.
If you just want to obscure the data (and put it beyond the level of most web users) you could always base64 encode the data, rather than encrypting it. Just be clear that you are NOT encrypting data and it is still possible to decode it. This approach is not a form of encryption.
If you decide to take that approach regardless, here are a few resources:
Client-side Encoding/Decoding
MSDN Reference on Encoding to Base64
Cheers.
You have two options for doing this:
Store the data on the server and give the user a token (e.g. a GUID) to pass along to retrieve the data. Since using the Session or TempData is not an option, you could store the viewmodel in the database, and then redirect the user with the token in the URL to retrieve it on the next request.
The other option would be to have the user pass the viewmodel in the URL as you're currently doing, but pass it in an encrypted format. For example, you could
serialize the model to JSON, encrypt it using one of .NET's built in encryption algorithms, and then redirect to the next action passing the encrypted string as your view model. Then you could change the target action to something like:
[AccessControl(Xri)]
public ActionResult TargetAction(string arg, string encryptedViewModel)
{
var decryptedString = Decrypt(encryptedViewModel) ; // supply the decrypt function to match your encryption
var viewModel = JsonConvert.DeserializeObject(decryptedString);
}

ASP.NET MVC does not deserialize JSON correctly when Conten-Type is missing

Using ASP.NET MVC 4, I have a controller that accepts a JSON structure:
public class SomeDto {
...
public Boolean IsUnicornAlive { get; set; }
...
}
[HttpPost]
public ActionResult DoSomething(SomeDto dto) {
...
}
Now if this POST request comes in without Content-Type specified:
{
...
"IsUnicornAlive":true
...
}
the action still gets called but IsUnicornAlive property would be false. Essentially this is a problem on the side that created the request, but still I would expect ASP to not treat it silently and not call my action with defaulted values. The most appropriate handling in this case would be a 4xx error, 415 ideally. What would be the easiest way to implement it? Or is there a way to know that default values were used inside the controller action?
Note: this question is not about ASP.NET WebApi which does not have this issue. This is specifically about MVC.
How about having a custom ModelBinder for SomeDTO and parsing the incoming data yourself and deciding whether to deduce the values, add a modelstate error, etc...
Look at the ModelState property of the Controller. For example ModelState.Keys.Count == 0 when the default value was used but you might find something even nicer in that object.

How to access a query string in MVC

I was getting the query string back using:
public ActionResult Index(int id)
{
var queryString = Request["myQueryString"];
}
Then I looked at:
help-testing-mvc3-controller-that-accesses-querystring
Which states:
It is against MVC's design pattern to use HttpRequest directly. You can access the query string variables on your action as parameters.
I don't really understand this. Is what I've done against the design pattern? If it is why is that and how could it be done?
It breaks the concept of model binding. It also gets complicated with unit testing and trying to new up a new HttpContext for a test. If it was just a parameter, you could just pass the value.
The preferred (and easier to read) method would be:
public ActionResult Index(int id, string myQueryString)
{
...
}
Your action method should take most of the data submitted from your form. One of the strengths of MVC is the model binding it has within it. Check out this page, as it has a good example of this:
http://www.codeproject.com/Articles/159749/ASP-NET-MVC-Model-Binding-Part1
You can accept literals (string, bool, etc.) but also strongly typed objects in your action methods.

Get header values in ASP.NET MVC

I have a requirement to capture the HTTP User Agent header coming in from a device, take the value and remove a 'uuid' This UUID can then be used to direct the device to the correct location to give it the files relevant to the device.
In webforms I was able to get it using
Request.ServerVariables["HTTP_USER_AGENT"]; //inside of Page_Load method
How would I go about this in MVC?
if in controller, you can easily get the header by this:
Request.Headers.GetValues("XXX");
if the name does not exist, it will throw an exception.
You do it the same way, in the controller:
Request.ServerVariables.Get("HTTP_USER_AGENT");
The Request object is part of ASP.NET, MVC or not.
See this for example.
It should be in the Request.Headers dictionary.
.Net 6 and above, this is how it works:
Request.Headers.TryGetValue("Auth-Token", out StringValues headerValues);
string jsonWebToken = headerValues.FirstOrDefault();
I prefer the new syntax which is more concise:
[HttpGet]
public async Task<IActionResult> GetAuth(FromHeader(Name = "Auth-Token")] string jwt) {
Headers without hypens -'s don't need the Name, they map automagically:
[HttpGet]
public async Task<IActionResult> GetAuth([FromHeader]string host) {
If there is anyone like me, who Googled to see how to get the Content-Type HTTP request header specifically, it's fairly easy:
Request.ContentType
With Core 3.1 and Microsoft.AspNetCore.Mvc.Razor 3.1, you can:
string sid = Request.Headers["SID"];
For whatever header variable you are looking for. Returns NULL if not found.

ASP.Net MVC : Sending JSON to Controller

I want to be able to send JSON as opposed to the standard QueryStrings when making a post to my controllers in ASP.Net MVC. I have the Front-End stuff working fine (building and then submitting my JSON objects).
The problem is on the controller side where the default ModelBinders that ship with the MVC framework do not support this.
I have seen a combination of ways around this, one of them is to apply a filter which takes the object as a parameter, uses a JSON library to de-serialise it, and adds that to the action parameters. This is not ideal.
The other, better, way is to use a custom Model Binder. All the ones I have seen though presume you will have only one model and that will be a class rather than a variable. If you have multiple ones it breaks down.
Has anyone else encountered this? One idea I had was if I could simply override how MVC deals with the FormCollection and intercept there, adding the values to the collection myself and hoping MVC can do the rest in it's normal fashion. Does anyone know if that is possible?
The key issue, I think, is that my problem is not with binding because my view models are no different to how they where before. The problem is getting the values from the JSON Post.
If I am correct MVC get's the values from the QueryString and puts it into the form collection which is then used for ModelBinding. So shouldn't the correct method be to change the way the FormCollection gets assigned?
Example of an action:
public ActionResult MyFirstAction(Int32 ID, PersonObject Person, ClassObject ClassDetails)
{
//etc
}
The normal binding works, JSON doesn't and all the example of Model Binders will not work either. My best solution so far is to convert the object to a dictionary and loop though each param and match it up. Doesn't seem ideal.
I use a custom model binder for json like this:
public class JsonModelBinder<T> : IModelBinder {
private string key;
public JsonModelBinder(string requestKey) {
this.key = requestKey;
}
public object BindModel(ControllerContext controllerContext, ...) {
var json = controllerContext.HttpContext.Request[key];
return new JsonSerializer().Deserialize<T>(json);
}
}
And then wire it up in Global.asax.cs like this:
ModelBinders.Binders.Add(
typeof(Product),
new JsonModelBinder<Product>("ProductJson"));
You can read more about this here: Inheritance is Evil: The Epic Fail of the DataAnnotationsModelBinder
EDIT
The JsonModelBinder should be used on the controller action parameter typed as Product only. The Int32 and ClassObject should fall back to the DefaultModelBinder. Are you experiencing a different result?

Resources