Database web app with ASP.NET MVC - c#

I am following this tutorial on how to create a simple database web application with ASP.NET MVC. I am having a problem with the 2nd Create controller method in the home controller (in Listing 4). Specifically, the error - when the web app is built - is with the AddToMovieSet method that actually saves the entries to the database.
It is worth noting that I am using VS 2016, whereas the tutorial uses a much older version (2008); this might be the reason to the problem. But, nevertheless, what is the code for this Create controller method?
This is the code in the Create action method in the home controller:
public ActionResult Create(Movie movieToCreate)
{
if (!ModelState.IsValid)
return View();
_db.AddToMovieSet(movieToCreate);
_db.SaveChanges();
return RedirectToAction("Index");
}

Make sure you have proper view created for this action method. Else create view or return view explicitly with name.

Related

Can a asp.net MVC controller class return Action Method and Json both?

Thanks for your time , I have a simple question, in an asp.net MVC application, inside controllers is it possible that along with some methods returning View (ActionMethods) other could act as (or return) Json as a Web API (could be called from external apps).
Just trying to do a proper separations, hence trying to understand.
Thanks much.
You can make an action function like an API. Try something like the this.
// Controller/Action
[HttpGet]
public ActionResult IAmSpecial()
{
if (Request.IsAjaxRequest())
{
string[] objects = new string[] { "Foo", "Bar" };
return Json(objects);
}
return View();
}
This will return the IAmSpecial view if you browse to {domain}/{Controller}/IAmSpecial while it will return a JSON result if you use an AJAX Http Get request on the same url.
while it is possible to have controller methods which return Json data only, there are a number of considerations when you want to expose that data outside of the UI app.
Since you have an MVC app, I expect you have users and a way to login. Your controllers would more than likely be secured in some way, which works for the internal users of the application. Now you want to add one method which effectively becomes an API, available outside of the application and calls to it will have to be authenticated somehow.
What I would suggest is to split this up. You can create a separate project, which is a WebAPI one, in the same solution. The code which prepares the data can live in a class library you can then reference in both your MVC and WebAPI projects.
Your MVC app can call it and then return a view with that data, the WebAPI calls it and simply returns the data. You can now decide on a way of securing your API, maybe using Identity Server or some other way and you can keep adding things to it, without affecting the UI layer.
Your second option is to make the MVC app use the API when it needs to retrieve data, so both your public clients and UI use the same thing.
Whichever option you use, the idea is to not duplicate anything and at the same time provide the security layers you need.

User ID is NULL when consuming an API in POSTMAN

I am trying to learn Web API and MVC. I, initially created a basic MVC project. Now, in the controllers folder ,I added a WebAPI controller.
In the WebAPI controller, I added the below code
public class SampleController : ApiController
{
[HttpPost]
public IHttpActionResult SampleData()
{
var userID = User.Identity.GetUserId();
return Ok();
}
}
The Method User.Identity.GetUserId() works fine in MVC.
I searched about on SO and found the following thread
User.Identity.GetUserId() method not working in a Web Api 2 Controller
This was not that helpful for me, as in my case I have added the API controller as part of the MVC project itself in the controllers folder.I have not created a separate project for WebAPI.
The above mentioned thread talks about the accesstoken already being present in code , whereas in my case, I dont see that code anywhere, as I just added only a single web api controller.
I am using POSTMAN for calling the API.
I have also looked at the following link
https://learn.microsoft.com/en-us/aspnet/web-api/overview/security/individual-accounts-in-web-api
In this case too, a separate WebAPI project is being talked about and not a single controller.
If I am mistaken somewhere, kindly guide me on the same.

C# MVC : Can you make a webservice that only takes POST actions

I was wondering if you can make a MVC webservice that only has HTTP POST methods.
For instance:
I use Selenium to open a page : http://localhost/main.html from .EXE application.
then my MVC app looks like this:
[HttpGet]
public ActionResult main()
{
return View();
}
[HttpPost]
public ActionResult Final(USER user)
{
saveUSER(user);
return null;
}
I just don't want MVC to open another page that the one that selenium used. I used to do this with an HttpWebRequest to the GET method, but even if I returned null, it would open a blank page AND then work out the rest of the logic.
The better way to test Post methods, services and repositories in a MVC Application is using functional or unit tests. There are nice frameworks that would help you to develop these tests.
I've been using Nunit to develop automated test in my work and in my own projects, the framework provide me the tools to develop functional and unit tests and runs all selenium integration tests inside him.

asp net httpselfhostserver for controllers that do not extend ApiController

Hi I am new to asp net programming and I am trying to test my asp net application using HttpSelfHostServer
link: http://www.c-sharpcorner.com/UploadFile/2b481f/self-hosting-in-Asp-Net-web-api/
by first setting up the server and then calling GET requests on my server on different controllers. (as described in the link)
This works perfectly when the controllers extend ApiController (which seems to be the base for asp net webapi applications) but it doesnt work for any other controller.
I am trying to get this to work with controllers that return views such as :
public class HomeController
: Controller
{
public ViewResult Index()
{
return View();
}
}
IS this not possible to do with the HttpSelfHostServer? Is there a workaround to this?

Problems trying to return the view with an API controller

I'm implementing a REST Web API. I'm using the examples from Adam Freeman's Pro ASP.NET MVC5 as a starting point but adapting it into the Web API way of doing it.
The below is my code:
public class AdminController : ApiController
{
private IUserRepository _repository;
public AdminController(IUserRepository repository)
{
_repository = repository;
}
public ActionResult Index()
{
return View(_repository.Users);
}
}
In the book, AdminController implemented Controller not ApiController, but if I do that then I get errors about there being no parameterless constructor. I need the constructor to take parameters so that I can inject the dependencies. So that's why I changed to ApiController but now it won't recognise View.
What do I need to use instead of View for an ApiController?
I did find this question but the answer was basically "you don't need to use an ApiController here, just use Controller" so that didn't help me.
You are having two different problems. Let's solve them separately.
1. Do I need to use ApiController or Controller?:
Someone already answered this here: Difference between ApiController and Controller in ASP.NET MVC.
The first major difference you will notice is that actions on Web API
controllers do not return views, they return data.
ApiControllers are specialized in returning data. For example, they
take care of transparently serializing the data into the format
requested by the client.
So, if you want to return a View you need to use the simple ol' Controller. The WebApi "way" is like a webservice where you exchange data with another service (returning JSON or XML to that service, not a View). So whenever you want to return a webpage (View) for a user you don't use the Web API.
In other words, the Web API is about returning data to another service (to return a JSON or XML), not to a user.
2. But if I use Controller then I get "parameterless constructor" errors.
Okay, now we've got to your real problem. Don't try to reinvent the wheel and fight with ASP.NET about doing dependency injection! A tool already exists to resolve dependency injection and sort out the "parameterless constructor" error: Ninject.
If you're already using Ninject and still getting that error, you're doing something wrong with Ninject. Try to repeat the installation and configuration steps, and see some tutorials or questions about parameterless error with Ninject use
An API controller is a controller which provides a RESTful response. You cannot return a view from it. Instead of doing that, consider returning a response (values) which forces the client that asks for an action to redirect to another controller (passing arguments if necessary) to return a view.
Your case does not look like you need an API; in this case just try this (change what you inherit):
public class AdminController : Controller
{
private IUserRepository _repository;
public AdminController(IUserRepository repository)
{
_repository = repository;
}
public ActionResult Index()
{
return View(_repository.Users);
}
}
I will try to explain what an API should do anyway. A web API should return just information. An HTTP response about what the action should do.
For example, to create a new customer, an API should have a method (decorated with POST) to get information from a client application (could be anything: web, windows, mobile, windows service, etc.). This information should be processed by the API (or other layers in a possible architecture) and return an HTTP status code, for example 200 - OK if it was fine or 400 - Bad Request if an error happened. So, when I said you should consider returning information, you could just return a DTO object to provide a result.
Both types of project use MVC principles, but they are used in a different context. Take a look at these articles:
Web Api 2.0 Tutorial
Difference between MVC and WEB API
Also take a look at the ASP.NET website about how they work:
ASP.NET WEB API
ASP.NET MVC
Use Controller to render your normal views. ApiController action only return data that is serialized and sent to the client.
But still you want to render view from APIcontroller, then there may be a another way, click on below link for reference :
https://aspguy.wordpress.com/2013/09/10/web-api-and-returning-a-razor-view/

Categories