EzDevInfo.com

asp.net-web-api interview questions

Top asp.net-web-api frequently asked interview questions

Who provides a WHOIS API? [closed]

Anyone can do WHOIS lookups through the whois command line tool or web based interfaces direct from the registrar but there are query limits which make commercial use difficult e.g. bulk checking of expiry dates on all your existing domains is not possible once you have more than x domains, where x is whatever the WHOIS server query limit is.

Are there any providers of WHOIS APIs?


Source: (StackOverflow)

How do I get ASP.NET Web API to return JSON instead of XML using Chrome?

Using the newer ASP.NET Web API, in Chrome I am seeing XML - how can I change it to request JSON so I can view it in the browser? I do believe it is just part of the request headers, am I correct in that?


Source: (StackOverflow)

Advertisements

Does IMDB provide an API?

I recently found a movie organizer application which fetches its data from the IMDB database.

Does IMDB provide an API for this, or any third party APIs available?


Source: (StackOverflow)

WCF vs ASP.NET Web API

I've spent a few months trying to grasp the concepts behind WCF and recently I've developed my first WCF service application.
I've struggled quite a bit to understand all the settings in the config file.
I am not convinced about the environment but it seems that you can do amazing stuff with it.
The other day I've found out that Microsoft has come out with a new thing called ASP.NET Web API.
For what I can read it's a RESTful framework, very easy to use and implement.
Now, I am trying to figure out what are the main differences between the 2 frameworks and if I should try and convert my old WCF service application with the new API.

Could someone, please, help me to understand the differences and usage of each?


Source: (StackOverflow)

How to secure an ASP.NET Web API

I want to build a RESTful web service using ASP.NET Web API that third-party developers will use to access my application's data.

I've read quite a lot about OAuth and it seems to be the standard, but finding a good sample with documentation explaining how it works (and that actually does work!) seems to be incredibly difficult (especially for a newbie to OAuth).

Is there a sample that actually builds and works and shows how to implement this?

I've downloaded numerous samples:

  • DotNetOAuth - documentation is hopeless from a newbie perspective
  • Thinktecture - can't get it to build

I've also looked at blogs suggesting a simple token-based scheme (like this) - this seems like re-inventing the wheel but it does have the advantage of being conceptually fairly simple.

It seems there are many questions like this on SO but no good answers.

What is everybody doing in this space?


Source: (StackOverflow)

Returning binary file from controller in ASP.NET Web API

I'm working on a web service using ASP.NET MVC's new WebAPI that will serve up binary files, mostly .cab and .exe files.

The following controller method seems to work, meaning that it returns a file, but it's setting the content type to application/json:

public HttpResponseMessage<Stream> Post(string version, string environment, string filetype)
{
    var path = @"C:\Temp\test.exe";
    var stream = new FileStream(path, FileMode.Open);
    return new HttpResponseMessage<Stream>(stream, new MediaTypeHeaderValue("application/octet-stream"));
}

Is there a better way to do this?


Source: (StackOverflow)

Difference between ApiController and Controller in ASP.NET MVC

I've been playing around with ASP.NET MVC 4 beta and I see two types of controllers now: ApiController and Controller.

I'm little confused at what situations I can choose a particular controller.

For ex: If I want to return a view then I've to use ApiController or the ordinary Controller? I'm aware that the WCF Web API is now integrated with MVC.

Since now we can use both controllers can somebody please point at which situations to go for the corresponding controller.


Source: (StackOverflow)

Best practice to call ConfigureAwait for all server-side code

When you have server-side code (i.e. some ApiController) and your functions are asynchronous - so they return Task<SomeObject> - is it considered best practice that any time you await functions that you call ConfigureAwait(false)?

I had read that it is more performant since it doesn't have to switch thread contexts back to the original thread context. However, with ASP.NET Web Api, if your request is coming in on one thread, and you await some function and call ConfigureAwait(false) that could potentially put you on a different thread when you are returning the final result of your ApiController function.

I've typed up an example of what I am talking about below:

public class CustomerController : ApiController
{
    public async Task<Customer> Get(int id)
    {
        // you are on a particular thread here
        var customer = await SomeAsyncFunctionThatGetsCustomer(id).ConfigureAwait(false);

        // now you are on a different thread!  will that cause problems?
        return customer;
    }
}

Source: (StackOverflow)

How to pass an array of integers to a asp.net web api rest service

I have asp.net web api rest service where I need to pass an array of integers. How can this be done in asp.net 4 web api.

public IEnumerable<Category> GetCategories(int[] categoryIds){
// code to retrieve categories from database
}

Url to access the above service

/Categories?categoryids=1,2,3,4

Source: (StackOverflow)

How To Accept a File POST - ASP.Net MVC 4 WebAPI

I'm using asp.net mvc 4 webapi beta to build a rest service. I need to be able to accept POSTed images/files from client applications. Is this possible using the webapi? Below is how action I am currently using. Does anyone know of an example how this should work?

[HttpPost]
public string ProfileImagePost(HttpPostedFile profileImage)
{
    string[] extensions = { ".jpg", ".jpeg", ".gif", ".bmp", ".png" };
    if (!extensions.Any(x => x.Equals(Path.GetExtension(profileImage.FileName.ToLower()), StringComparison.OrdinalIgnoreCase)))
    {
        throw new HttpResponseException("Invalid file type.", HttpStatusCode.BadRequest);
    }

    // Other code goes here

    return "/path/to/image.png";
}

Source: (StackOverflow)

Best practice to return errors in ASP.NET Web API

I have concerns on the way that we returns errors to client.

Do we return error immediately by throwing HttpResponseException when we get an error:

public void Post(Customer customer)
{
    if (string.IsNullOrEmpty(customer.Name))
    {
        throw new HttpResponseException("Customer Name cannot be empty", HttpStatusCode.BadRequest) 
    }
    if (customer.Accounts.Count == 0)
    {
         throw new HttpResponseException("Customer does not have any account", HttpStatusCode.BadRequest) 
    }
}

Or we accumulate all errors then send back to client:

public void Post(Customer customer)
{
    List<string> errors = new List<string>();
    if (string.IsNullOrEmpty(customer.Name))
    {
        errors.Add("Customer Name cannot be empty"); 
    }
    if (customer.Accounts.Count == 0)
    {
         errors.Add("Customer does not have any account"); 
    }
    var responseMessage = new HttpResponseMessage<List<string>>(errors, HttpStatusCode.BadRequest);
    throw new HttpResponseException(responseMessage);
}

This is just a sample code, it does not matter either validation errors or server error, I just would like to know the best practice, the pros and cons of each approach.


Source: (StackOverflow)

JSONP with ASP.NET Web API

I am working on creating a new set of services in ASP.MVC MVC 4 using the Web API. So far, it's great. I have created the service and gotten it to work, and now I am trying to consume it using JQuery. I can get back the JSON string using Fiddler, and it seems to be ok, but because the service exists on a separate site, trying to call it with JQuery errors with the "Not Allowed". So, this is clearly a case where I need to use JSONP.

I know that the Web API is new, but I'm hoping someone out there can help me.

How do I make a call to a Web API method using JSONP?


Source: (StackOverflow)

Throw HttpResponseException or return Request.CreateErrorResponse?

After reviewing an article Exception Handling in ASP.NET Web API I am a bit confused as to when to throw an exception vs return an error response. I am also left wondering whether it is possible to modify the response when your method returns a domain specific model instead of HttpResponseMessage...

So, to recap here are my questions followed by some code with case #s:

Questions

Questions regarding Case #1

  1. Should I always use HttpResponseMessage instead of a concrete domain model, so that the message can be customized?
  2. Can the message be customized if you are returning concrete domain model?

Questions regarding Case #2,3,4

  1. Should I be throwing an exception or returning error response? If the answer is "it depends", can you give situations/examples on when to use one vs the other.
  2. What is the difference between throwing HttpResponseException vs Request.CreateErrorResponse ? The output to client seems identical...
  3. Should I always use HttpError to "wrap" response messages in errors (whether the exception is thrown or error response returned)?

Case Samples

// CASE #1
public Customer Get(string id)
{
    var customer = _customerService.GetById(id);
    if (customer == null)
    {
        var notFoundResponse = new HttpResponseMessage(HttpStatusCode.NotFound);
        throw new HttpResponseException(notFoundResponse);
    }
    //var response = Request.CreateResponse(HttpStatusCode.OK, customer);
    //response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(300));
    return customer;
}        

// CASE #2
public HttpResponseMessage Get(string id)
{
    var customer = _customerService.GetById(id);
    if (customer == null)
    {
        var notFoundResponse = new HttpResponseMessage(HttpStatusCode.NotFound);
        throw new HttpResponseException(notFoundResponse);
    }
    var response = Request.CreateResponse(HttpStatusCode.OK, customer);
    response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(300));
    return response;
}

// CASE #3
public HttpResponseMessage Get(string id)
{
    var customer = _customerService.GetById(id);
    if (customer == null)
    {
        var message = String.Format("customer with id: {0} was not found", id);
        var errorResponse = Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
        throw new HttpResponseException(errorResponse);
    }
    var response = Request.CreateResponse(HttpStatusCode.OK, customer);
    response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(300));
    return response;
}

// CASE #4
public HttpResponseMessage Get(string id)
{
    var customer = _customerService.GetById(id);
    if (customer == null)
    {
        var message = String.Format("customer with id: {0} was not found", id);
        var httpError = new HttpError(message);
        return Request.CreateErrorResponse(HttpStatusCode.NotFound, httpError);
    }
    var response = Request.CreateResponse(HttpStatusCode.OK, customer);
    response.Content.Headers.Expires = new DateTimeOffset(DateTime.Now.AddSeconds(300));
    return response;
}

Update

To help further demonstrate cases #2,3,4 the following code snippet highlights several options that "can happen" when a customer is not found...

if (customer == null)
{
    // which of these 4 options is the best strategy for Web API?

    // option 1 (throw)
    var notFoundMessage = new HttpResponseMessage(HttpStatusCode.NotFound);
    throw new HttpResponseException(notFoundMessage);

    // option 2 (throw w/ HttpError)
    var message = String.Format("Customer with id: {0} was not found", id);
    var httpError = new HttpError(message);
    var errorResponse = Request.CreateErrorResponse(HttpStatusCode.NotFound, httpError);
    throw new HttpResponseException(errorResponse);

    // option 3 (return)
    var message = String.Format("Customer with id: {0} was not found", id);
    return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);
    // option 4 (return w/ HttpError)
    var message = String.Format("Customer with id: {0} was not found", id);
    var httpError = new HttpError(message);
    return Request.CreateErrorResponse(HttpStatusCode.NotFound, httpError);
}

Source: (StackOverflow)

ASP.NET Web API Authentication

I am looking to authenticate a user from a client application while using the ASP.NET Web API. I have watched all the videos on the site and also read this forum post.

Putting the [Authorize] attribute correctly returns a 401 Unauthorized status. However, I need to know how to allow a user to log in to the API.

I want to provide user credentials from an Android application to the API, get the user logged in, and then have all subsequent API calls pre-authenticated.


Source: (StackOverflow)

User Authentication in ASP.NET Web API

This topic has been incredibly confusing for me. I am a rookie in HTTP apps but need to develop an iPhone client that consumes JSON data from somewhere. I chose Web API from MS because it seemed easy enough but when it comes to authenticating users, things get quite frustrating.

I am amazed how I've not been able to find a clear example of how to authenticate an user right from the login screen down to using the Authorize attribute over my ApiController methods after several hours of Googling.

This is not a question but a request for an example of how to do this exactly. I have looked at the following pages:

Even though these explain how to handle unauthorized requests, these do not demonstrate clearly something like a LoginController or something like that to ask for user credentials and validate them.

Anyone willing to write a nice simple example or point me in the right direction, please?

Thanks.


Source: (StackOverflow)