How to extend (System.Net.Http)HttpClient Http Verbs? - asp.net-mvc

Is it possible to add a new arbitrary HTTP Verb to System.Net.Http HttpClient?
Case in question:
I developed a WebAPI for an MVC-based document managment system.
The API supports:
GET - fetch a document, POST - create a new document, PUT - update a document, DELETE - delete a document.
I also need to support: PRINT - print a document, EMAIL - email a document.
It is easy to add the VERBs on the MVC side. Add the [AcceptVerbs("PRINT")] decoration and you are done.
BUT I need to instruct the developers using my API how to access it. Since they are using HttpClient my problem is: How will these VERBs be consumed using the HttpClient?
Dror

Those are not standard HTTP verbs. I would not recommend you using them. If you insist on using them you could use the SendAsync method which allows you to specify the HTTP verb you want to use:
using (var client = new HttpClient())
{
var request = new HttpRequestMessage(new HttpMethod("PRINT"), "http://example.com");
var result = client.SendAsync(request);
}

Related

Return view to client from web service

I need to develop a payment gateway web service which can be called from all my other application.I use ASP.net web API for this.
I created an HTTP post service which accepts XML as an input parameter.I will parse this XML.if there is sufficient information it will be redirected to payment page or otherwise it will show a page which collects the sufficient data from user. So it must return a view to user and custom error codes and messages.
These are my needs and I want to know which is the best way to accomplish this.
Can I use web API controller or MVC controller for this?
How will the client show the view returned? Inside iframe is not considered as a good choice for me.Is there any other good ways to show the page?
You can use RazorEngine to parse view in WebApi.
var templatePath = HttpContext.Current.Server.MapPath("~/Views/Payment/Form.cshtml");
var templateContent = File.ReadAllText(templatePath);
var templateString = Razor.Parse(templateContent, new ClassA());
return Ok(new {
ErrorCode = "000",
Html = templateString
});
Your can refer this link https://antaris.github.io/RazorEngine/ for quickstart.

Alternative to using Webclient to get HTML output

A product I've inherited is using WebClient to read HTML from a MVC based site. Each page is a different type of e-mail, so in order to compose and send an e-mail they use WebClient to request a URL and download the string.
var outputHtml = string.Empty;
using (WebClient client = new WebClient())
{
client.Encoding = Encoding.UTF8;
outputHtml = client.DownloadString(emailURL);
}
return outputHtml;
Is there a way to remove the need to host this email based site but retain most of this code. I guess what I need to do is pass my request to the controller and retrieve the output after the razor engine has passed the view model through the cshtml page.
Is that possible?
There are many ways you could render a Razor view to a string. One possibility is to use RazorEngine. Another possibility is to use some specifically designed framework for this purpose such as Postal.

What's the best way to call a REST API from MVC4

MVC4 provides a very simple way to return serialized objects from HTTP requests. What's the best way to call a REST or other JSON/XML API from an MVC4 application? I could construct an HTTP request, send it, then deserialize the result, but I was hoping for something simpler. My application runs on multiple servers and one server needs to talk to the other via the web API. So, both servers have the same class definitions. I'm hoping there is some fairly transparent way to get MVC to deserialize as cleanly as it serializes content.
This is an example of how I call an MVC4 WebAPI from a WPF application. You should be able to adjust according to your needs. Hope this helps...
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://192.200.1.3:9594/");
// Add an Accept header for JSON format.
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("EmployeeTest/TestApi");
if (response.IsSuccessStatusCode) {
var employee = response.Content.ReadAsAsync<Employee>().Result;
tbName.Text = employee.Name;
tbPhone.Text = employee.Phone;
}

How to get the raw binary content in Grails controller

after many days of search and many unsuccessful tries, I hope that the community knows a way to achieve my task:
I want to use grails as a kind of a proxy to my solr backend. By this, I want to ensure that only authorized requests are handled by solr. Grails checks the provided collection and the requested action and validated the request with predefined user based rules. Therefore, I extended my grails URL mapping to
"/documents/$collection/$query" {
controller = "documents"
action = action = [GET: "proxy_get", POST: "proxy_post"]
}
The proxy_get method works fine even when the client is using solrJ. All I have to to is to forward the URL request to solr and to reply with the solr response.
However, in the proxy_post method, I need to get the raw body data of the request to forward it to solr. SolrJ is using javabin for that and I was not able so far to get the raw binary request. The most promising approach was this:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(solrUrl);
InputStream requestStream = request.getInputStream();
ContentType contentType = ContentType.create(request.getContentType());
httpPost.setEntity(new ByteArrayEntity(IOUtils.toByteArray(requestStream), contentType));
httpPost.setHeader("Content-Type", request.getContentType())
HttpResponse solrResponse = httpClient.execute(httpPost);
However, the transferred content is empty in case of javabin (e.g. when I add a document using solrJ).
So my question is, whether there is any possibility to get to the raw binary post content so that I can forward the request to solr.
Mathias
try using Groovy HttpBuilder. It has a powerful low-level API, while providing groovyness

Handling WebDAV requests on MVC action

I have an existing MVC3 application which allows users to upload files and share them with others. The current model is that if a user wants to change a file, they have to delete the one there and re-upload the new version. To improve this, we are looking into integrating WebDAV to allow the online editing of things like Word documents.
So far, I have been using the .Net server and client libraries from http://www.webdavsystem.com/ to set the website up as a WebDAV server and to talk with it.
However, we don't want users to interact with the WebDAV server directly (we have some complicated rules on which users can do what in certain situations based on domain logic) but go through the previous controller actions we had for accessing files.
So far it is working up to the point where we can return the file and it gives the WebDAV-y type prompt for opening the file.
The problem is that it is always stuck in read-only mode. I have confirmed that it works and is editable if I use the direct WebDAV URL but not through my controller action.
Using Fiddler I think I have found the problem is that Word is trying to talk negotiate with the server about the locking with a location that isn't returning the right details. The controller action for downloading the file is "/Files/Download?filePath=bla" and so Word is trying to talk to "/Files" when it sends the OPTIONS request.
Do I simply need to have an action at that location that would know how to respond to the OPTIONS request and if so, how would I do that response? Alternatively, is there another way to do it, perhaps by adding some property to the response that could inform Word where it should be looking instead?
Here is my controller action:
public virtual FileResult Download(string filePath)
{
FileDetails file = _fileService.GetFile(filePath);
return File(file.Stream, file.ContentType);
}
And here is the file service method:
public FileDetails GetFile(string location)
{
var fileName = Path.GetFileName(location);
var contentType = ContentType.Get(Path.GetExtension(location));
string license ="license";
var session = new WebDavSession(license) {Credentials = CredentialCache.DefaultCredentials};
IResource resource = session.OpenResource(string.Format("{0}{1}", ConfigurationManager.AppSettings["WebDAVRoot"], location));
resource.TimeOut = 600000;
var input = resource.GetReadStream();
return new FileDetails { Filename = fileName, ContentType = contentType, Stream = input };
}
It is still very early days on this so I appreciate I could be doing this in entirely the wrong way and so any form of help is welcome.
In the end it seems that the better option was to allow users to directly talk to the WebDAV server and implement the authentication logic to control it.
The IT Hit server has extensions that allow you to authenticate against the forms authentication for the rest of the site using basic or digest authentication from Office. Using that along with some other customisations to the item request logic gave us what we needed.
This is exactly what i did for a MVC 4 project.
https://mvc4webdav.codeplex.com/

Resources