reading my json response from a post request i sent - c#

I made a post request class that I could re-use to make POST requests to an external api and return the objects they send me (JSON):
class PostRequest
{
private Action<DataUpdateState> Callback;
public PostRequest(string urlPath, string data, Action<DataUpdateState> callback)
{
Callback = callback;
// form the URI
UriBuilder fullUri = new UriBuilder(urlPath);
fullUri.Query = data;
// initialize a new WebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fullUri.Uri);
request.Method = "POST";
// set up the state object for the async request
DataUpdateState dataState = new DataUpdateState();
dataState.AsyncRequest = request;
// start the asynchronous request
request.BeginGetResponse(new AsyncCallback(HandleResponse),
dataState);
}
private void HandleResponse(IAsyncResult asyncResult)
{
// get the state information
DataUpdateState dataState = (DataUpdateState)asyncResult.AsyncState;
HttpWebRequest dataRequest = (HttpWebRequest)dataState.AsyncRequest;
// end the async request
dataState.AsyncResponse = (HttpWebResponse)dataRequest.EndGetResponse(asyncResult);
if (dataState.AsyncResponse.StatusCode.ToString() == "OK")
{
Callback(dataState); // THIS IS THE LINE YOU SHOULD LOOK AT :)
}
}
}
public class DataUpdateState
{
public HttpWebRequest AsyncRequest { get; set; }
public HttpWebResponse AsyncResponse { get; set; }
}
}
the Callback method gets the datastate object and pushes it to this function:
public void LoadDashboard( DataUpdateState dataResponse )
{
Stream response = dataResponse.AsyncResponse.GetResponseStream();
//Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
//StreamReader readStream = new StreamReader(response, encode);
//readStream.Close();
Deployment.Current.Dispatcher.BeginInvoke(() => {
App.RootFrame.Navigate(new Uri("/Interface.xaml", UriKind.RelativeOrAbsolute));
});
}
I'm now unsure of how to get the body of that reply that has been sent to me from the API. It is returning a json format, I need to be able to map it to a nice C# class and use it to display stuff on the phone.
I can't find an example that doesn't use JSON.NET (which doesn't have an assembly for windows phone 8)
This is error I get installing HTTPClient class:
Attempting to resolve dependency 'Microsoft.Bcl (≥ 1.1.3)'.
Attempting to resolve dependency 'Microsoft.Bcl.Build (≥ 1.0.4)'.
Successfully installed 'Microsoft.Bcl.Build 1.0.10'.
Successfully installed 'Microsoft.Bcl 1.1.3'.
Successfully installed 'Microsoft.Net.Http 2.2.13'.
Successfully added 'Microsoft.Bcl.Build 1.0.10' to UnofficialPodio.
Executing script file ***\packages\Microsoft.Bcl.Build.1.0.10\tools\Install.ps1'.
This reference cannot be removed from the project because it is always referenced by the compiler.
This reference cannot be removed from the project because it is always referenced by the compiler.
This reference cannot be removed from the project because it is always referenced by the compiler.
This reference cannot be removed from the project because it is always referenced by the compiler.
Executing script file ***\packages\Microsoft.Bcl.Build.1.0.10\tools\Uninstall.ps1'.
Successfully uninstalled 'Microsoft.Bcl 1.1.3'.
Successfully uninstalled 'Microsoft.Bcl.Build 1.0.10'.
Install failed. Rolling back...
Failed to add reference to 'System.IO'.
"{
\"access_token\": \"123803120312912j\",
\"token_type\": \"bearer\",
\"ref\": {
\"type\": \"user\",
\"id\": 123123
},
\"expires_in\": 28800,
\"refresh_token\": \"234234f23f423q432f\"
}"
...
public class Auth
{
[DataMember(Name = "access_token")]
public string AccessToken { get; set; }
[DataMember(Name = "token_type")]
public string TokenType { get; set; }
[DataMember(Name = "expires_in")]
public string ExpiresIn { get; set; }
[DataMember(Name = "refresh_token")]
public string RefreshToken { get; set; }
//[DataMember(Name = "ref")]
//public string Ref { get; set; }
}

To get the response data you need to call GetResponseStream() on the HttpWebResponse object and then read from the stream. Something like this:
using (Stream s = response.GetResponseStream())
{
using (TextReader textReader = new StreamReader(s, true))
{
jsonString = textReader.ReadToEnd();
}
}
To get the data from the json string, you need to create a data contract class to describe the json data exactly like this:
[DataContract]
public class ApiData
{
[DataMember(Name = "name")] <--this name must be the exact name of the json key
public string Name { get; set; }
[DataMember(Name = "description")]
public string Description { get; set; }
}
Next you can deserialize the json object from the string:
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ApiData));
ApiData obj = (ApiData)serializer.ReadObject(stream);
return obj;
}
WebRequest will work fine, but I would recommend installing the NuGet package for the HttpClient class. It makes life much simpler. for instance, you could make the above request code in just a few lines:
HttpClient httpClient = new HttpClient();
HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), escapedUrl);
HttpResponseMessage response = await httpClient.SendAsync(msg);
In answer to you question below, here is the generic json converter code that I use:
public static class JsonHelper
{
public static T Deserialize<T>(string json)
{
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
T obj = (T)serializer.ReadObject(stream);
return obj;
}
}
public static string Serialize(object objectToSerialize)
{
using (MemoryStream ms = new MemoryStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(objectToSerialize.GetType());
serializer.WriteObject(ms, objectToSerialize);
ms.Position = 0;
using (StreamReader sr = new StreamReader(ms))
{
return sr.ReadToEnd();
}
}
}
}

JSON.Net does support windows phone 8, it's available as a portable class library according to this answer.
Just try adding the package via nuget...

Related

Why do two (almost) similar methods(using c#) of uploading a file to Slack cause different outcomes?

so this question baffels me. I'll post quite abit of code to explain this one. First, I have and "old" version of code(c#), which I used to post messages and files to Slack. And this code works fine for me! The method of interest is the following:
public class PostMessage
{
private string _token = "xoxp-MyToken";
public string token { get { return _token; } }
public string channel { get; set; }
public string text { get; set; }
public MultipartFormDataContent UploadFile()
{
var requestContent = new MultipartFormDataContent();
var fileContent = new StreamContent(GetFile.ReadFile());
requestContent.Add(new StringContent(token), "token");
requestContent.Add(new StringContent(channel), "channels");
requestContent.Add(fileContent, "file", Path.GetFileName(GetFile.path));
return requestContent;
}
public static class GetFile
{
public static string path = #"C:\Users\f.held\Desktop\Held-Docs\Download.jpg";
public static FileStream ReadFile()
{
FileInfo fileInfo = new FileInfo(path);
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
return fs;
}
}
Here is my client:
public class SlackClient
{
public Uri _method { get; set; }
private readonly HttpClient _httpClient = new HttpClient {};
public SlackClient(Uri webhookUrl)
{
_method = webhookUrl;
}
public async Task<HttpResponseMessage> UploadFileAsync(MultipartFormDataContent requestContent)
{
var response = await _httpClient.PostAsync(_method, requestContent);
return response;
}
}
And I call all of this in this Main:
public static void Main(string[] args)
{
Task.WaitAll(TalkToSlackAsync());
private static async Task TalkToSlackAsync()
{
var webhookUrl = new Uri("https://slack.com/api/files.upload");
var slackClient = new SlackClient(webhookUrl);
PostMessage PM = new PostMessage();
PM.channel = "DCW21NBHD";
var cont = PM.UploadFile();
var response = await slackClient.UploadFileAsync(cont);
string content = await response.Content.ReadAsStringAsync();
}
}
So far, so good! But now it gets interesting. I build a similar version, in which I use Newtonsoft's Json NuGet-package
Now, first the code:
the client:
public async Task<HttpResponseMessage> SendFileAsync(MultipartFormDataContent requestContent)
{
_httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "xoxp-MyToken");
var response = await _httpClient.PostAsync(UriMethod, requestContent);
return response;
}
the same Filestram-method for reading the file:
public class Message
{
public class GetFile // Just pass a path here as parameter!
{
public static string path = #"C:\Users\f.held\Desktop\Held-Docs\Download.jpg";
public static FileStream ReadFile()
{
FileInfo fileInfo = new FileInfo(path);
FileStream fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
return fs;
}
}
the Json-class which I serialize:
public class JsonObject
{
[JsonProperty("file")]
public string file { get; set; }
[JsonProperty("channels")]
public string channels { get; set; }
}
And the Main:
class MainArea
{
public static void Main( string[] args)
{
try
{
Task.WaitAll(SendMessage());
}
catch(Exception dudd)
{
Console.WriteLine(dudd);
Console.ReadKey();
}
}
private static async Task SendMessage()
{
var client = new BpsHttpClient("https://slack.com/api/files.upload");
JsonObject JO = new JsonObject();
JO.channels = "DCW21NBHD";
var Json = JsonConvert.SerializeObject(JO, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
var StringJson = new StringContent(Json, Encoding.UTF8, "multipart/form-data");
var DeSon = JsonConvert.DeserializeObject(Json);
Console.WriteLine(DeSon);
Console.ReadKey();
var requestContent = new MultipartFormDataContent();
var fileContent = new StreamContent(Message.GetFile.ReadFile());
requestContent.Add(fileContent, "file", Path.GetFileName(Message.GetFile.path));
requestContent.Add(StringJson);
var ResponseFile = await client.SendFileAsync(requestContent);
Console.WriteLine(ResponseFile);
Console.ReadKey();
}
}
So, both SEEM to work. But the latter of these methods does NOT post the file to the declared channel - it merely uploads it to Slack. Which would be fine, because I could then work with the 'public_url' to publicise it on any channel. BUT - BIG BUT - with the first method, it immediately loads it to my channel! And it tells me so in the response I get from Slack. The responses are in both exactly the same - except for the timestamps and file_id etc. obviously. But the ending is different!
Here is the ending of the response from the old version:
"shares":{"private":{"DCW21NBHD":[{"reply_users":[],"reply_users_count":0,"reply_count":0,"ts":"1544025773.001700"}]}},"channels":[],"groups":[],"ims":["DCW21NBHD"]}}
and here is the answer from the new version:
"shares":{},"channels":[],"groups":[],"ims":[]}}
Okay now, why on god's green earth does one method do that and the other one does not? :D
Thanks to anybody who has some insight and knowledge on this specific "issue" and is willing to share!
As stated in the documentation for files.upload:
Present arguments as parameters in application/x-www-form-urlencoded
querystring or POST body. This method does not currently accept
application/json.
So the reason this does not work is that you are trying to provide the API parameters like channels as JSON, when this method does not support JSON. The result is that those properties are ignore, which is why the image is uploaded, but not shared in the designated channel.
To fix it simply provide your parameters as application/x-www-form-urlencoded querystring as you did in your 1st example.
Note that in general only a subset of the Slack API methods support using JSON for providing the parameters as listed here. If you want to use JSON, please double-check if the API method supports it, or stick with x-www-form-urlencoded (which is the standard for POST) to be on the safe side.

How to convert Object and view it on WebAPI?

Here is my question,
I got a Web API and client(winform), client will send out data with a Serialize Object. My Web API do have received and return a response to client. But I can't view the data on Web API, I do have try using Deserialize Object and convert it into string but not working neither.
Please help me,Thanks!
Here is my code:
Client
private string WebApiPost(string sParam, string sJson)
{
var client = new HttpClient();
var content = new StringContent(sJson, Encoding.UTF8, "application/json");
var response = client.PostAsync(sWebAPI_URL + sParam, content).Result;
var body = response.Content.ReadAsStringAsync().Result;
return body;
}
This is my Web API
public object Post([FromBody]object hL7)
{
//what should I do???
//I've tried set hL7 into string but it wont get any data;
//I've also tried deserialize it but will get 500 internal server error.
return hL7;
}
This is my WebAPI model
public class HL7MID
{
public string LOC { get; set; }
public string COMPANY { get; set; }
}
public class HL7MID_List
{
public string sMSG { get; set; }
public List<HL7MID> data = new List<HL7MID>();
}
Because sJson matches HL7MID, you can use that type in as a paramter of your Post function, and just use that type.
public HL7MID Post([FromBody]HL7MID hL7)
{
//use hL7 here
return hL7;//also since you know the return type, changing that to HL7MID is suggested
}

How to Seriailize an c# object into Json, while using httpClient?

I have a little program which should communicate with "Slack". In an older Version I used "Dictionary<string, string>" and then put them into UrlEncodedContent - which worked fine.
Now I am trying to create a Json-object, using Newtonsoft's Nuget-package and (in my opinion) formatting my object the way they say on their website.
Problem is, when I try to make a simple request, my program just runs to one specific line in the code(var response = await _httpClient.SendAsync(request);) and then it just ends. It doesn't throw an exception or display any kind of message, it simply ends on this line. I went through my code step by step while debugging, that's how I know it ends on exactly this line. And I just don't know why!
Now my code:
First, my object...
namespace BPS.Slack
{
public class JsonObject
{
//generally needed parameters
[JsonProperty("ok")]
public bool ok { get; set; }
[JsonProperty("error")]
public string error { get; set; }
[JsonProperty("channel")]
public string channel { get; set; }
[JsonProperty("token")]
private string token = "xoxp-MyToken";
[JsonProperty("as_user")]
public bool as_user = false;
[JsonProperty("username")]
public string username { get;set; }
//--------------------------------
//only needed for textmessages
[JsonProperty("text")]
public string text { get; set; }
//--------------------------------
//for posting messages with data attached
[JsonProperty("initial_comment")]
public string initial_comment { get; set; }
[JsonProperty("file")]
public string file { get; set; }
[JsonProperty("channels")]
public string channels { get; set; }
//--------------------------------
//for getting the latest message from a channel
[JsonProperty("count")]
public string count = "1";
[JsonProperty("unreads")]
public bool unreads = true;
}
}
now the client:
namespace BPS.Slack
{
public class BpsHttpClient
{
private readonly HttpClient _httpClient = new HttpClient { };
public Uri UriMethod { get; set; }
public BpsHttpClient(string webhookUrl)
{
UriMethod = new Uri(webhookUrl);
}
public async Task<HttpResponseMessage> UploadFileAsync(MultipartFormDataContent requestContent)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, UriMethod);
request.Content = requestContent;
var response = await _httpClient.SendAsync(request);
return response;
}
}
}
and the main
namespace TestArea
{
class MainArea
{
public static void Main( string[] args)
{
try
{
Task.WhenAll(SendMessage());
}
catch(Exception ass)
{
Console.WriteLine(ass);
Console.ReadKey();
}
}
private static async Task SendMessage()
{
var client = new BpsHttpClient("https://slack.com/api/im.history");
JsonObject JO = new JsonObject();
JO.channel = "DCW21NBHD";
var Json = JsonConvert.SerializeObject(JO);
var StringJson = new StringContent(Json, Encoding.UTF8);
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(StringJson);
var Response = await client.UploadFileAsync(content);
string AnswerContent = await Response.Content.ReadAsStringAsync();
Console.WriteLine(AnswerContent);
Console.ReadKey();
}
}
}
I had the same problem in my older version, BUT only as I wanted to DEserialize an answer I got from Slack. It had to do with my object I tried do deserialize the answer into. But this time I can not figure out what's wrong. But, as I said, I do not have any experience with using serialized objects as Json-property to send requests... anyone has an idea what is wrong with my code?
EDIT: This problem is kinda solved. But there is a follow up problem.
Okay, I found out that the reason for the abprubt termination was the
Task.WhenAll(SendMessage());
it should be
Task.WaitAll(SendMessage()); Why??? Somebody said I should use WhenAll, but obviously it doesn't work properly in this case...
Now I get a response from Slack, but now a different problem has arisen. When I use this method:
public async Task<HttpResponseMessage> UploadFileAsync(MultipartFormDataContent requestContent)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, UriMethod);
request.Content = requestContent;
var response = await _httpClient.SendAsync(request);
return response;
}
I allways get the answer:
{"ok":false,"error":"invalid_form_data"}
so I tried to explicitly tell it the 'mediaType', I tried "application/json" and others, but with all of them I get the same error. Here is the full method that calls the upper mehtod:
private static async Task SendMessage()
{
var client = new BpsHttpClient("https://slack.com/api/chat.postMessage");
JsonObject JO = new JsonObject();
JO.channel = "DCW21NBHD";
JO.text = "This is so much fun :D !";
var Json = JsonConvert.SerializeObject(JO, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
var StringJson = new StringContent(Json, Encoding.UTF8, "application/json");
var requestContent = new MultipartFormDataContent();
requestContent.Add(StringJson);
var Response = await client.UploadFileAsync(requestContent);
string AnswerContent = await Response.Content.ReadAsStringAsync();
}
When I use this method:
public async Task<HttpResponseMessage> SendMessageAsync(FormUrlEncodedContent content)
{
var response = await _httpClient.PostAsync(UriMethod, content);
return response;
}
so bascially I am passing "FormUrlEncodedContent" instead of "MultipartFormDataContent" in this, and then I get the response I want and can work wiht it. BUT this i of little use to me since I have to use "MultipartFormDataContent" to be able to send files with my requests.
Anyone have an idea what is failing here? Why does it not like the one content-type but the other one? I'd be gratefull for tipps and ideas!
You are serializing your object to Json and then adding it to a Multipart body, that's quite strange. Unless you're uploading binary data (eg Files), there is no need to use MultipartFormDataContent.
You are can directly post your JsonObject serialized as JSON:
public async Task<HttpResponseMessage> PostJsonAsync(StringContent content)
{
var response = await client.PostAsync(url, content);
return response;
}
var client = new BpsHttpClient("https://slack.com/api/im.history");
JsonObject JO = new JsonObject();
JO.channel = "DCW21NBHD";
var Json = JsonConvert.SerializeObject(JO);
var StringJson = new StringContent(Json, Encoding.UTF8);
var Response = await client.PostJsonAsync(content);
Also this is should be POST on the UploadFileAsync function.
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, UriMethod);
so I figured out that in the Main() the problem was this:
Task.WhenAll(SendMessage());
I should instead use:
Task.WaitAll(SendMessage());
Anyone who has more knowledge on this, please elaborate why!

Json Webrequest To C# Object

im currently developing an app which has an webrequest: I got the following class (got it from json2csharp converter):
class InventoryJsonData
{
public class RootObject
{
public bool Success { get; set; }
public object Error { get; set; }
public double Price { get; set; }
public string Username { get; set; }
}
}
Then i did the following coding:
ValueLoadingIndicator.IsActive = true;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(JsonBaseuri + IDInput.Text);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
There is only one RootObject in the JSON Data. How do i get now the Price value so i can convert it into string and display it. I dont know what i need to add as c# code.
If you got helpful links to JSON c# tutorials and webrequest which are about this topic and can help me to move on they are appreciated as well.
Take a look and Newtonsoft Json.NET library: http://www.newtonsoft.com/json
You could also use WebClient class for you request - it's simpler to use.
Here is example code:
var url = JsonBaseuri + IDInput.Text;
var wc = new WebClient {Proxy = null};
var json = wc.DownloadString(url);
var responseModel = JsonConvert.DeserializeObject<InventoryJsonData>(json);
var price = responseModel.RootObject.Price;
HttpClient http = new System.Net.Http.HttpClient();
HttpResponseMessage response = await http.GetAsync(JsonBaseuri + IDInput.Text.ToString());
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
MessageDialog x = new MessageDialog(content, "JsonData");
This code gets me the Json File in windows universal apps ;) then i deserialize it -> read the answers above

How do I post data to MVC Controller using HttpWebRequest?

I am trying to post data to MVC controller action but have been unsuccessful so far.
Here is the structure of the post data:
private string makeHttpPostString(XmlDocument interchangeFile)
{
string postDataString = "uid={0}&localization={1}&label={2}&interchangeDocument={3}";
InterchangeDocument interchangeDocument = new InterchangeDocument(interchangeFile);
using (var stringWriter = new StringWriter())
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
interchangeFile.WriteTo(xmlTextWriter);
string interchangeXml = HttpUtility.UrlEncode(stringWriter.GetStringBuilder().ToString());
string hwid = interchangeDocument.DocumentKey.Hwid;
string localization = interchangeDocument.DocumentKey.Localization.ToString();
string label = ConfigurationManager.AppSettings["PreviewLabel"];
return (string.Format(postDataString, hwid, localization, label, interchangeXml));
}
}
Here is the request:
HttpWebRequest webRequest = (HttpWebRequest) WebRequest.Create(controllerUrl);
webRequest.Method = "POST";
// webRequest.ContentType = "application/x-www-form-urlencoded";
string postData = makeHttpPostString(interchangeFile);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
webRequest.ContentLength = byteArray.Length;
using (Stream dataStream = webRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
HttpWebResponse webresponse = (HttpWebResponse) webRequest.GetResponse();
When I set the contenttype of the request to "application/x-www-form-urlencoded" GetReponse() fails with server error code 500. When I comment that out and only httpencode the xml data, "interchangeXml", the post is sent but only the 3rd parameter, "label" reaches the controller. The others are null.
What is the correct way to post values to a controller action when one of those values is xml data?
Thanks!
Update
I am send all the parameter with the exception of the XML via the query string. However, the problem now is that I do not know how to access the posted data in the controller action. Can someone tell me how I access the xml from the HttpRequest from with my Controller Action?
Update
I have refactored the above code to use the suggests made to me by Darin. I am recieveing an internal server error (500) using the WebClient UploadValues().
Action:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult BuildPreview(PreviewViewModel model)
{
...
}
Request:
private string PostToSxController(XmlDocument interchangeFile, string controllerUrl)
{
var xmlInterchange = new InterchangeDocument(interchangeFile);
using (var client = new WebClient())
{
var values = new NameValueCollection()
{
{"uid", xmlInterchange.DocumentKey.Hwid},
{"localization", xmlInterchange.DocumentKey.Localization.ToString()},
{"label", ConfigurationManager.AppSettings["PreviewLabel"]},
{"interchangeDocument", interchangeFile.OuterXml }
};
byte[] result = null;
try
{
result = client.UploadValues(controllerUrl, values);
}
catch(WebException ex)
{
var errorResponse = ex.Response;
var errorMessage = ex.Message;
}
Encoding encoding = Encoding.UTF8;
return encoding.GetString(result);
}
}
Route:
routes.MapRoute(
"BuildPreview",
"SymptomTopics/BuildPreview/{model}",
new { controller = "SymptomTopics", action = "BuildPreview", model = UrlParameter.Optional }
);
Too complicated and unsafe your client code with all those requests and responses. You are not encoding any of your request parameters, not to mention this XML which is probably gonna break everything if you don't encode it properly.
For this reason I would simplify and leave the plumbing code about encoding, etc... to the .NET framework:
using (var client = new WebClient())
{
var values = new NameValueCollection
{
{ "uid", hwid },
{ "localization", localization },
{ "label", label },
{ "interchangeDocument", interchangeFile.OuterXml },
};
var result = client.UploadValues(controllerUrl, values);
// TODO: do something with the results returned by the controller action
}
As far as the server side is concerned, as every properly architected ASP.NET MVC application, it would obviously use a view model:
public class MyViewModel
{
public string Uid { get; set; }
public string Localization { get; set; }
public string Label { get; set; }
public string InterchangeDocument { get; set; }
}
with:
[HttpPost]
public ActionResult Foo(MyViewModel model)
{
// TODO: do something with the values here
...
}
Obviously this could be taken a step further by writing a view model reflecting the structure of your XML document:
public class Foo
{
public string Bar { get; set; }
public string Baz { get; set; }
}
and then your view model will become:
public class MyViewModel
{
public string Uid { get; set; }
public string Localization { get; set; }
public string Label { get; set; }
public Foo InterchangeDocument { get; set; }
}
and the last part would be to write a custom model binder for the Foo type that will use a XML serializer (or whatever) to deserialize back the InterchangeDocument POSTed value into a Foo instance. Now that's serious business.
I'm wrestling the same beast over here: Trying to set up a controller action as Xml endpoint
You may be getting the internal server error because either you have page validation on (solution: addotate with ValidateInput(false)), or you're not sending an Accept-Encoding header with your request. I would very much like to hear how I can get MVC to accept posted input without the Accept-Encoding HTTP header...
I just found that you can call a controller, even a dependency injected one, even from a Web Forms code behind using the "T4MVC" Nuget package:
https://github.com/T4MVC/T4MVC

Categories