Delete WebApi FromURI binding - asp.net

I am trying to create a .NET5 WebApi delete method in a controller class where this method receives several "ids" that will be used for deleting some entities.
I realized when building the delete request on the client side that specifying a content does not make sense. So I was guided to pass ids on the Uri, hence the use of the "FromUri" attribute:
// DELETE: api/ProductionOrders/5
[HttpDelete("ProductionOrders")]
public IActionResult DeleteProductionOrder([System.Web.Http.FromUri]int[] ids)
{
//code
}
If this is a reasonable approach, is there a better way to build this Uri from the client-side? Imagine instead of an array of ints I had a complex type. How can I serialized this and put into the Uri?
For this example I end up building up a URI like this:
http://localhost:51081/api/ProductionOrders?ids=25563&ids=25533

Personally, if I have to pass a List or a complex type I would map values from the Body via JSON. The DELETE allow using body. And then just decorate your param with [FromBody] attribute.
Despite some recommendations not to use the message body for DELETE requests, this approach may be appropriate in certain use cases.
This allows better extensibility in case you need to change how the data is coming.
In your case with ids I’d create new class like this:
public class RequestEntity {
[JsonPropertyName("Ids")]
public List<int> Ids { get; set; }
}
And then when calling this method, send the Body along with the request.
{
"Ids": [25392, 254839, 25563]
}
In a future you can pass complex objects just by changing what is send to server and implement complex logic.

Related

Spring mvc: is there a way to call another controller, get the response and fill it to a model attribute?

I have two mvc style endpoints returning templatefile names as view names, in the same classpath: /source and /target. The source_template has a variable which needs to be filled by contents of another template, say target_template.
#RestController
class SomeController {
#GetMapping("/source")
public String source(Model model) {
model.addAttribute("attr1", /*call endpoint /target and add the response of parsed template 'target_template' here */);
return "source_template";
}
#GetMapping("/target")
public String target(Model model) {
model.addAttribute("attr2", "good");
//may be continue the nested invocation n number of times
return "target_template";
}
}
given the source_template.html:
Hai, $attr1
and the target_template.html:
this has been a $attr2 day
having said, i invoke the url /source, I should get "Hai, this has been a good day".
I can just call the target() method directly, but that would not render the template. Or I should directly use the templating engine apis to link the template file, put the context object, parse the template and return the string , which defeats the whole purpose of spring mvc. Or I can use resttemplate, but that requires an absolute url, and performance would take a hit. So, is there any other way to do it ?

How to send integer array as a parameter from endpoint without querystring from url in asp.net core webapi

I have an endpoint that has a parameter that type of integer array.I want send some value from body as a json string.When I tried it , I was getting null value from parameter so I tried to send integer array from url but happen problem about of url length so I want to know that is possible to send it from request body or how to fix url length problem for 5.000 item
request body that I tried
{
"Ids": [349]
}
endpoint function
[HttpGet]
public void GetModels([FromBody]List<int> Ids)
{
}
First, in general including a body in a GET request is often not considered very RESTful. It is no longer specifically "banned" by RFC, but it is not typical. That said, you can make this work in ASP.Net Core using the [FromBody] attribute.
The issue has to do with how you are formatting your JSON body. Using the signature for GetModels that you have listed above, the JSON body doesn't match the parameters. Your JSON represents a top-level object with a property Ids that is an array of int, not just an array of it (or List).
If you want to use public void GetModels([FromBody]List<int> Ids) then your JSON body should simply be an array (e.g. [349,350,351]) and nothing else (no brackets, no "Ids" property name).
If you want to use the JSON body you list above, then you need another class to use for model binding, a DTO. That DTO would look something like:
public class IdDto
{
public List<int> Ids { get; set; }
}
and then your GetModels method would look like:
[HttpGet]
public void GetModels([FromBody] IdDto idDto)
{
var myIds = idDto.Ids;
}
Lastly, be sure that your GET request has a Content-Type set to application/json or ASP.Net will return a 415 "Unsupported Media Type".

WCF single vs multiple operations ?. design ideas

We are developing a CRM application. All the business logic and data access go through WCF services. We have 2 options for communication between WCF and client (at the moment: ASP.NET MVC 2)
One option is create method for each operations. Example
GetCustomers()
GetCustomersWithPaging(int take, int skip)
GetCustomersWithFilter(string filter)
GetCustomersWithFilterPaging(string filter, int take, int skip)
or // new .net 4 feature
GetCustomers(string filter = null, int take = 0, int skip = 0)
... list goes..
Another option is create a generic single service operation called
Response InvokeMessage(Messege request). Example
wcfservice.InvokeMessage(
new CustomerRequest {
Filter = "google",
Paging = new Page { take = 20, skip = 5}
});
// Service Implementation.
public Response InvokeMessage(Message request)
{
return request.InvokeMessage();
}
InvokeMessage = generic single service call for all operation.
CustomerRequest = Inherited class from Message abstract class, so I can create multiple classes from Message base class depend on the input requirements.
Here is the CustomerRequest class.
public class CustomerRequest : Message
{
public string Filter {get;set;}
public Page Paging {get;set} // Paging class not shown here.
Public override Response InvokeMessage()
{
// business logic and data access
}
}
EDIT
public abstract class Message
{
public abstract Response InvokeMessage();
}
// all service call will be through InvokeMessage method only, but with different message requests.
Basically I could avoid each service call's and proxy close etc..
One immediate implication with this approach is I cannot use this service as REST
What is the recommended approach if the service needs to call lots of methods?
thanks.
If you use the facade pattern you can have both.
First, build your services using the first option. This allows you to have a REST interface. This can be used externally if required.
You can then create a facade that uses Invoke message style, this translates the request based on the parameters and calls one of the individual services created in the first step.
As to the question of multiple specific operations vs one general query - either approach could be valid; defining fine-grained vs coarse-grained operations is to some degree a matter of taste.
When faced with a similar requirement in our RESTful service, I've chosen to create a filter class that reads parameters from the query-string, available thusly:
public NameValueCollection ReadQuerystring()
{
return WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters;
}
The larger issue that I see here is that you're subclassing Message for your operation parameters - is there a reason why you're doing that? The best practice is to create data contracts (objects annotated with [DataContract] attributes) for such a purpose.

What is the best way to "fake" DELETE and PUT methods using JAX-RS?

I've just started to use Jersey to create a RESTful API for my site. Its a wonderful change from having to roll my own support for RESTful services in Java. One thing I just can't seem to figure out is how to "fake" a DELETE and PUT method.
Jersey supports the annotations #PUT and #DELETE, however many Load-Balancers will not allow these methods through. In the past I've relied on the ability to define a custom HTTP header (e.g. x-method-override: DELETE) and "tunneling" within a POST request.
Has anyone found a way to bind a method using Jersey/JAX-RS annotations to custom headers? Alternatively, is there a better way around lack of support for PUT and DELETE?
Well here is how I've decided to handle the situation within my API. Its relatively simple and doesn't require much additional coding. To illustrate consider a RESTful api for Address:
#Path("/address")
public class AddressService {
#GET
#Produces("application/xml")
public StreamingOutput findAll() { ... }
#POST
#Produces("application/xml")
#Consumes("application/x-www-form-urlencoded")
public StreamingOutput create(...) { ... }
//
// This is the alternative to a "PUT" method used to indicate an "Update"
// action. Notice that the #Path expects "/id/{id}" which allows
// us to bind to "POST" and not get confused with a "Create"
// action (see create() above).
//
#POST
#Produces("application/xml")
#Consumes("application/x-www-form-urlencoded")
#Path("/id/{id}")
public StreamingOutput update(#PathParam("id") Long id, ...) { ... }
//
// This is the typical "GET" method with the addition of a check
// for a custom header "x-method-override" which is designed to
// look for inbound requests that come in as a "GET" but are
// intended as "DELETE". If the methodOverride is set to "DELETE"
// then the *real* delete() method is called (See below)
//
#GET
#Produces("application/xml")
#Path("/id/{id}")
public StreamingOutput retrieve(
#PathParam("id") Long id,
#HeaderParam("x-method-override") String methodOverride)
{
if (methodOverride != null && methodOverride.equalsIgnoreCase("DELETE")) {
this.delete(id);
}
...
}
//
// This is the typical "DELETE" method. The onlything special about it is that
// it may get invoked by the #GET equivalent is the "x-method-override" header
// is configured for "DELETE"
//
#DELETE
#Produces("application/xml")
#Path("/id/{id}")
public StreamingOutput retrieve(#PathParam("id") Long id) { ... }
}
It's not really REST anymore, but in a similar situation we defined POST /collection/ to be insert (as normal), POST /collection/{id} to be update, POST /collection/{id} without body to be delete.

Access/use the same object during a request - asp.net

i have a HttpModule that creates an CommunityPrincipal (implements IPrincipal interface) object on every request. I want to somehow store the object for every request soo i can get it whenever i need it without having to do a cast or create it again.
Basically i want to mimic the way the FormsAuthenticationModule works.
It assigns the HttpContext.User property an object which implements the IPrincipal interface, on every request.
I somehow want to be able to call etc. HttpContext.MySpecialUser (or MySpecialContext.MySpecialUser - could create static class) which will return my object (the specific type).
I could use a extension method but i dont know how to store the object so it can be accessed during the request.
How can this be achieved ?
Please notice i want to store it as the specific type (CommunityPrincipal - not just as an object).
It should of course only be available for the current request being processed and not shared with all other threads/requests.
Right now i assign my CommunityPrincipal object to the HttpContext.User in the HttpModule, but it requires me to do a cast everytime i need to use properties on the CommunityPrincipal object which isnt defined in the IPrincipal interface.
I'd recommend you stay away from coupling your data to the thread itself. You have no control over how asp.net uses threads now or in the future.
The data is very much tied to the request context so it should be defined, live, and die along with the context. That is just the right place to put it, and instantiating the object in an HttpModule is also appropriate.
The cast really shouldn't be much of a problem, but if you want to get away from that I'd highly recommend an extension method for HttpContext for this... this is exactly the kind of situation that extension methods are designed to handle.
Here is how I'd implement it:
Create a static class to put the extension method:
public static class ContextExtensions
{
public static CommunityPrinciple GetCommunityPrinciple(this HttpContext context)
{
if(HttpContext.Current.Items["CommunityPrinciple"] != null)
{
return HttpContext.Current.Items["CommunityPrinciple"] as CommunityPrinciple;
}
}
}
In your HttpModule just put the principal into the context items collection like:
HttpContext.Current.Items.Add("CommunityPrincipal", MyCommunityPrincipal);
This keeps the regular context's user property in the natural state so that 3rd party code, framework code, and anything else you write isn't at risk from you having tampered with the normal IPrincipal stroed there. The instance exists only during the user's request for which it is valid. And best of all, the method is available to code as if it were just any regular HttpContext member.... and no cast needed.
Assigning your custom principal to Context.User is correct. Hopefully you're doing it in Application_AuthenticateRequest.
Coming to your question, do you only access the user object from ASPX pages? If so you could implement a custom base page that contains the cast for you.
public class CommunityBasePage : Page
{
new CommunityPrincipal User
{
get { return base.User as CommunityPrincipal; }
}
}
Then make your pages inherit from CommunityBasePage and you'll be able to get to all your properties from this.User.
Since you already storing the object in the HttpContext.User property all you really need to acheive you goal is a Static method that acheives your goal:-
public static class MySpecialContext
{
public static CommunityPrinciple Community
{
get
{
return (CommunityPrinciple)HttpContext.Current.User;
}
}
}
Now you can get the CommunityPrinciple as:-
var x = MySpecialContext.Community;
However it seems a lot of effort to got to avoid:-
var x = (CommunityPrinciple)Context.User;
An alternative would be an Extension method on HttpContext:-
public static class HttpContextExtensions
{
public static CommunityPrinciple GetCommunity(this HttpContext o)
{
return (CommunityPrinciple)o.User;
}
}
The use it:-
var x = Context.GetCommunity();
That's quite tidy but will require you to remember to include the namespace where the extensions class is defined in the using list in each file the needs it.
Edit:
Lets assume for the moment that you have some really good reason why even a cast performed inside called code as above is still unacceptable (BTW, I'd be really interested to understand what circumstance leads you to this conclusion).
Yet another alternative is a ThreadStatic field:-
public class MyModule : IHttpModule
{
[ThreadStatic]
private static CommunityPrinciple _threadCommunity;
public static CommunityPrinciple Community
{
get
{
return _threadCommunity;
}
}
// Place here your original module code but instead of (or as well as) assigning
// the Context.User store in _threadCommunity.
// Also at the appropriate point in the request lifecyle null the _threadCommunity
}
A field decorated with [ThreadStatic] will have one instance of storage per thread. Hence multiple threads can modify and read _threadCommunity but each will operate on their specific instance of the field.

Resources